<?php

require_once('functions/pageLoad.php');
loginRequired();
$user_session = explode("_", $_SESSION['user']);
$user_id = $user_session[0];

if(isset($_GET['token'])){

	$rs['sms_remaining'] = 0;

	$sql = "SELECT payments.id, amount, sms_remaining, SMS.id AS sms_id, tradesman.id AS tradesman_id  
	FROM payments 
	LEFT JOIN SMS on payments.user_id = SMS.user_id 
	LEFT JOIN tradesman ON payments.user_id = tradesman.user_id 
	WHERE payments.user_id = '".$user_id."' AND token = '".mysql_real_escape_string($_GET['token'])."' AND payment_made IS NULL";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$rows = mysql_num_rows($query);

	if($rows == '1'){

	$sql = "UPDATE payments SET payment_made = NOW() WHERE id = '".$rs['id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	if(mysql_affected_rows() == '1'){

	$sql = "SELECT sms FROM sms_packages WHERE price = '".$rs['amount']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$sms_rs=mysql_fetch_assoc($query);
	
	$new_remaining = $rs['sms_remaining'] + $sms_rs['sms'];
	
	$sql = "UPDATE SMS SET sms_remaining = '".$new_remaining."' WHERE id = '".$rs['sms_id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	if(mysql_affected_rows() == '0'){

	$sql = "INSERT INTO SMS (user_id, tradesman_id, sms_remaining) VALUES ('".$user_id."', '".$rs['tradesman_id']."', '".$new_remaining."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	}

	$content = '<div class="yellow_box"><p>Thank you, your order has been processed and your SMS allowance has been updated. You now have '.$new_remaining.' SMS.<br /><br /><a href="/my-account"><strong>Return to my account</strong></a></p></div>';

	}

	}

}

$page_title = 'Purchase complete';

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1>Purchase complete</h1>

<?php echo $content; ?>

<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>